package flink;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.io.Serializable;
import java.time.Duration;

/**
 * Created by liujian on 2021/5/12.
 */
public class WatermarkDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.socketTextStream("192.168.62.37", 8889)
//                .filter(keyword -> StringUtils.isNotEmpty(keyword))
                .map(new Splitter())
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Order>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((order, timestamp) -> order.getEventTime())
                ).keyBy(Order::getName)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .sum("money")
                .print();
        env.execute();

    }

    private static class Splitter implements MapFunction<String, Order> {
        @Override
        public Order map(String value) throws Exception {
            String name = value.split(" ")[0];
            Integer money = Integer.parseInt(value.split(" ")[1]);
            Long eventTime = Long.parseLong(value.split(" ")[2]);
            return new Order(name, money, eventTime);
        }
    }



    public static class Order implements Serializable {
        private String name;
        private Integer money;
        private Long eventTime;

        public Order() {
        }

        public Order(String name, Integer money, Long eventTime) {
            this.name = name;
            this.money = money;
            this.eventTime = eventTime;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getMoney() {
            return money;
        }

        public void setMoney(Integer money) {
            this.money = money;
        }

        public Long getEventTime() {
            return eventTime;
        }

        public void setEventTime(Long eventTime) {
            this.eventTime = eventTime;
        }


    }
}
